package egovframework.npqs.pqi.mobile;

import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageButton;

import com.sds.BizAppLauncher.gov.aidl.GovController;
import com.slidingmenu.lib.SlidingMenu;

import egovframework.npqs.pqi.mobile.activity.approve.ApproveList;
import egovframework.npqs.pqi.mobile.activity.disinfection.DisinfectionResultList;
import egovframework.npqs.pqi.mobile.activity.exportquarantineresult.ExportQuarantineResultList;
import egovframework.npqs.pqi.mobile.activity.quarantinerequest.QuarantineRequestList;
import egovframework.npqs.pqi.mobile.activity.quarantineresult.QuarantineResultList;
import egovframework.npqs.pqi.mobile.menu.MenuControl;

public class ActivityMain extends BaseActivity implements android.view.View.OnClickListener{

	// log에서 출력할 tag
    private static final String TAG = ActivityMain.class.getSimpleName();
	public static Activity am;
	private Button menu01_btn, menu02_btn, menu03_btn, menu04_btn, menu05_btn;
	private ImageButton loginBtn;
	private AppStatus myapp;
	private static ActivityMain instance = null;
	private GovController controller;
	
	public static ActivityMain getInstance() {
		return instance;
	}
	public static void clearInstance() {
		instance = null;
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		controller = GovController.getInstance(this);
		try {
			requestWindowFeature(Window.FEATURE_NO_TITLE);
			setContentView(R.layout.activity_main);
			myapp = (AppStatus) getApplicationContext();
			setSlidingMenu(savedInstanceState);
			init();
			listener();
			
		} catch (Exception e) {
			
		}
	}
	

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		try {
			if (KeyEvent.KEYCODE_MENU == keyCode) {
				toggle();
			}
		} catch (Exception e) {

		}
		return super.onKeyDown(keyCode, event);
	}

	void init() {
		instance = this;
		am = this;
		
		menu01_btn = (Button)findViewById(R.id.menu_01_btn);
		menu02_btn = (Button)findViewById(R.id.menu_02_btn);
		menu03_btn = (Button)findViewById(R.id.menu_03_btn);
		menu04_btn = (Button)findViewById(R.id.menu_04_btn);
		menu05_btn = (Button)findViewById(R.id.menu_05_btn);
		
		loginBtn = (ImageButton)findViewById(R.id.btn_login);
		loginBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				onBackPressed();				
			}
		});
		
		menu01_btn.setOnClickListener(this);
		menu02_btn.setOnClickListener(this);
		menu03_btn.setOnClickListener(this);
		menu04_btn.setOnClickListener(this);
		menu05_btn.setOnClickListener(this);
	}
	

	private void listener() {
		
	}
	


	@Override
	public void onBackPressed() {
		if(MenuControl.tagetFragment != null){
			Fragment fragment = getVisibleFragment(0);
	         if(fragment instanceof BaseFragment) {
	            BaseFragment basefragment = (BaseFragment)fragment;
	            String tag = basefragment.getTag();
	            Fragment frag = getFragmentTag(tag);
	            if (frag != null) {
	               basefragment.Onback();
	               if(myapp.isQuarantineState()){
	               }else{
	            	   myapp.setQuarantineState(true);
	            	   return;
	               }
	            }
	         }
	         
			FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
			if(MenuControl.tagetFragment != null){
				ft.remove(MenuControl.tagetFragment);
				MenuControl.tagetFragment = null;
			}
			ft.commit();		
			
		}else{
			new AlertDialog.Builder(ActivityMain.this)
			.setTitle("종료")
			.setMessage("어플을 종료하시겠습니까??")
			.setPositiveButton("예", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					try {
						finish();
					} catch (Exception e) {

					}
				}
			})
			.setNegativeButton("아니오", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					try {
						
					} catch (Exception e) {

					}
				}
			})
			.setCancelable(false)
			.show();				
		}
	}
	
	protected int getVisibleFragmentCount(){
	      try{
	            FragmentManager fragmentManager = getSupportFragmentManager();
	             List<android.support.v4.app.Fragment> fragments = fragmentManager.getFragments();
	             
	             return fragments.size();
	      }catch(Exception e){
	         e.printStackTrace();
	      }
	       return 0;
	   }	

	// private Fragment mContent;
	private void setSlidingMenu(Bundle savedInstanceState) {
		if (findViewById(R.id.menu_frame) == null) {
			setBehindContentView(R.layout.menu_frame);
			getSlidingMenu().setSlidingEnabled(true);
			getSlidingMenu()
					.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
		} else {
			// add a dummy view
			View v = new View(this);
			setBehindContentView(v);
			getSlidingMenu().setSlidingEnabled(false);
			getSlidingMenu().setTouchModeAbove(SlidingMenu.TOUCHMODE_NONE);
		}

		// set the Above View Fragment
		/*
		 * if (savedInstanceState != null) mContent =
		 * getSupportFragmentManager().getFragment(savedInstanceState,
		 * "mContent"); if (mContent == null) mContent = new MenuControl();
		 */

		// set the Behind View Fragment
		getSupportFragmentManager().beginTransaction()
				.replace(R.id.menu_frame, new MenuControl()).commit();

		// customize the SlidingMenu
		SlidingMenu sm = getSlidingMenu();
		sm.setBehindOffsetRes(R.dimen.slidingmenu_offset);
		sm.setShadowWidthRes(R.dimen.shadow_width);
		sm.setShadowDrawable(R.drawable.shadow);
		
		sm.setBehindScrollScale(0.25f);
		sm.setFadeDegree(0.25f);
		sm.setFadeDegree(0f);
	}


	@Override
	public void onResume() {
		super.onResume();
	}
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.menu_01_btn:
			QuarantineRequestList quarantineRequest = new QuarantineRequestList();
			addFragmentReplace(R.id.base_frame, quarantineRequest, QuarantineRequestList.class.getName());
			break;
			
		case R.id.menu_02_btn:
			QuarantineResultList incomeResultList = new QuarantineResultList();
			addFragmentReplace(R.id.base_frame, incomeResultList, QuarantineResultList.class.getName());			
			break;
			
		case R.id.menu_03_btn:
			DisinfectionResultList disinfectionResultList = new DisinfectionResultList();
			addFragmentReplace(R.id.base_frame, disinfectionResultList, DisinfectionResultList.class.getName());			
			break;
			
		case R.id.menu_04_btn:
			ApproveList approveList = new ApproveList();
			addFragmentReplace(R.id.base_frame, approveList, ApproveList.class.getName());			
			break;	
			
		case R.id.menu_05_btn:
			ExportQuarantineResultList exportList = new ExportQuarantineResultList();
			addFragmentReplace(R.id.base_frame, exportList, ApproveList.class.getName());			
			break;	
			
		default:
			break;
		}
		
	}
	
	@Override
	protected void onPause() {
		super.onPause();
	}
	
	//행정용 애플리케이션을 종료할때 필수로 작성해야하는 코드
	/*@Override
	protected void onDestroy() {
		super.onDestroy();
		System.out.println("onDestroy 함수 호출");
		loginActivity.asyncTaskDisConnectVPN();
		loginActivity.asyncTaskServiceBroker();
		Log.i("Destroy Method call...", "VPN 터널을종료하는 등의 동작을 자동으로 수행합니다.");
		GovController.getInstance(this).unBindService();
	}*/
	@Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            Log.d("Service Broker", "연결 해제");
            controller.unBindService(); // 서비스 연결을 해제한다.
        } catch (IllegalArgumentException iae) {
            Log.e(TAG, iae.getMessage().toString());
        }
    }
}
